#pragma once
#include <QObject>
#include <QMap>
#include <QString>
#include <QMutex>
#include <QtSql/QSqlDatabase>
#include "ConnectionPool.h"

class DatabaseManager : public QObject
{
    Q_OBJECT
public:
    // 数据库配置结构体
    struct DatabaseConfig
    {
        ConnectionPool::DBType type;
        QString name;
        QString host;
        int port;
        QString user;
        QString password;
        int maxConnections;
        QString validationQuery;
    };

    // 单例访问
    static DatabaseManager& instance();

    ConnectionPool* pool(const QString& name = "default");
    bool hasPool(const QString& poolName);
    // 核心接口
    void addDatabase(const QString& poolName);
    void removeDatabase(const QString& poolName);
    QSqlDatabase connection(const QString& poolName = "default");
    void releaseConnection(QSqlDatabase conn);

    // 事务管理
    bool transaction(const QString& poolName);
    bool commit(const QString& poolName);
    bool rollback(const QString& poolName);

    // 状态监控
    int activeConnections(const QString& poolName) const;
    int idleConnections(const QString& poolName) const;
    QStringList availablePools() const;

private:
    explicit DatabaseManager(QObject* parent = nullptr);
    ~DatabaseManager();

    QMap<QString, ConnectionPool*> m_pools;

    mutable QMutex m_poolMutex;    // 正确声明为 QMutex
};
